package com.zzf.rpc;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;

/**
 * @author zzf
 * @date 2018/8/13 13:45.
 */
public class TCPTransport {

    private String host;
    private int port;

    public TCPTransport(String host, int port) {
        this.host = host;
        this.port = port;
    }

    private Socket newSocket() {
        //创建链接
        System.out.println("创建链接");

        Socket socket;
        try {
            socket = new Socket(host, port);
            return socket;
        } catch (Exception e) {
            throw new RuntimeException("new Socket error");
        }
    }

    public Object send(RpcRequest request) {
        Socket socket;
        ObjectOutputStream os=null;
        ObjectInputStream ois=null;
        try {
            //信息发送
            socket = newSocket();
            os = new ObjectOutputStream(socket.getOutputStream());
            os.writeObject(request);

            os.flush();
            ois = new ObjectInputStream(socket.getInputStream());
            Object result = ois.readObject();
            ois.close();
            os.close();
            return result;
        } catch (Exception e) {
            throw new RuntimeException("发生远程调用error",e);
        } finally {
            try {
                ois.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
